<template>
  <div id="luckysheet-container" class="excel-editor"></div>
</template>

<script setup>
import { onMounted, onUnmounted, watch } from 'vue';
import 'jquery-mousewheel';
import luckysheet from 'luckysheet';

// 接收父组件传递的表格数据
const props = defineProps({
  content: {
    type: Object,
    default: () => ({ data: [], config: {} })
  }
});

// 向父组件传递表格变化
const emit = defineEmits(['change', 'destroy']);

// 初始化Luckysheet
const initLuckysheet = () => {
  if (!props.content.data || !document.getElementById('luckysheet-container')) return;
  console.log('jQuery loaded:', typeof $ !== 'undefined');
  console.log('mousewheel plugin loaded:', typeof $.fn.mousewheel !== 'undefined');
  luckysheet.create({
    container: 'luckysheet-container',
    data: props.content.data,
    config: {
      ...props.content.config,
      enableAddRow: true,
      enableAddCol: true
    },
    // 表格变化时触发事件
    change: (changes) => {
      emit('change', changes);
    },
    showtoolbar: true,
    showinfobar: true,
    showsheetbar: true
  });
};

// 监听父组件传递的内容变化，重新初始化
watch(() => props.content, (newVal) => {
  if (newVal.data && newVal.data.length > 0) {
    initLuckysheet();
  }
}, { deep: true });

// 生命周期：挂载时初始化
onMounted(() => {
  initLuckysheet();
});

// 生命周期：卸载时销毁实例
onUnmounted(() => {
  if (window.luckysheet) {
    window.luckysheet.destroy();
    window.luckysheet = null;
    emit('destroy');
  }
});
</script>

<style scoped>
.excel-editor {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
#luckysheet-container {
  width: 100%;
  height: 100%;
}
</style>